﻿using System;
using System.Linq;
using System.Windows.Media.Imaging;
using Microsoft.Surface.Presentation.Controls;
using System.ComponentModel;
using System.Xml.Linq;
using System.Net;
using System.Windows.Threading;
using System.IO;
using System.Windows.Media;
using System.Windows;
using System.Windows.Shapes;

namespace WikipediaSurfaceBrowser
{    
    public partial class ImagePad : SurfaceUserControl
    {
        private string _source;
        private BackgroundWorker _bw;

        private ApplicationSettings _settings = new ApplicationSettings();
        private static string _resolveImageUrl = "http://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo&iiprop=url&titles={0}&format=xml";

        public ImagePad()
        {
            InitializeComponent();
        }

        public string SourceFileName
        {
            get
            {
                return Uri.UnescapeDataString(System.IO.Path.GetFileName(_source));
            }
        }

        public string LocalSource
        {
            get
            {
                return _source;
            }

            set
            {
                _source = value;

                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = File.OpenRead(_source);
                bi.EndInit();                

                ImageBrush ib = new ImageBrush();
                ib.ImageSource = bi;
                ib.Stretch = Stretch.Uniform;
                contentBorder.Background = ib;                
            }
        }

        public string Source
        {
            get
            {
                return _source;
            }

            set
            {
                _source = value;

                _bw = new BackgroundWorker();
                _bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
                _bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bw_RunWorkerCompleted);
                _bw.RunWorkerAsync(Uri.EscapeUriString(_source));               
            }
        }

        void _bw_DoWork(object sender, DoWorkEventArgs e)
        {            
            e.Result = GetCommonsImagePath((string) e.Argument);
        }

        void _bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result == null)
            {
                return;
            }

            this.LocalSource = (string)e.Result;                      
        }

        private string GetCommonsImagePath(string imageName)
        {
            string imageUrl = null;

            string[] imageNameParts = imageName.Split(new char[] { ':' });

            string wikiCache = _settings.CacheFolder + System.IO.Path.DirectorySeparatorChar + imageNameParts[0] + System.IO.Path.DirectorySeparatorChar + imageNameParts[1];

            if (!File.Exists(wikiCache))
            {
                WebClient w = new WebClient();
                XDocument d = XDocument.Parse(w.DownloadString(String.Format(_resolveImageUrl, imageName)));

                XElement e = d.Descendants("ii").FirstOrDefault<XElement>();

                if (e != null && e.Attribute("url") != null)
                {
                    imageUrl = e.Attribute("url").Value;
                }

                if (imageUrl == null)
                {
                    return null;
                }

                if (!Directory.Exists(System.IO.Path.GetDirectoryName(wikiCache)))
                {
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(wikiCache));
                }

                w.DownloadFile(imageUrl, wikiCache);            
            }
                        
            return wikiCache;
        }
        

        private void cmdPaintOnOff_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            paintArea.IsHitTestVisible = (bool)cmdPaintOnOff.IsChecked;            
            paintArea.MaxWidth = paintArea.ActualWidth;
            paintArea.MaxHeight = paintArea.ActualHeight;            
        }

        private void cmdClose_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ((ScatterView)((ScatterViewItem)Parent).Parent).Items.Remove(Parent);
        }

        private void Color_Checked(object sender, RoutedEventArgs e)
        {
            if (sender.GetType() != typeof(SurfaceRadioButton))
            {
                return;
            }

            Rectangle r = (Rectangle)((SurfaceRadioButton)sender).Content;
            paintArea.DefaultDrawingAttributes.Color = ((SolidColorBrush)r.Fill).Color;
        }

        private void cmdClear_Click(object sender, RoutedEventArgs e)
        {
            paintArea.Strokes.Clear();
        }

        private void SurfaceUserControl_Loaded(object sender, RoutedEventArgs e)
        {
                        
        }
    }
}
